﻿namespace Widgets.MoviesForMyBlog
{
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Xml;
    using System.Security.Cryptography;
    using System.IO;
    using System.Net;
    using App_Code.Controls;

    /// <summary>
    /// Created By: Jason Deatherage
    /// Released: March 2010
    /// If you want to modify this code please leave my credit 
    /// in the code and link to my site on your webpage.
    /// Thanks.
    /// </summary>
    /// 
    public partial class Edit : WidgetEditBase
    {
        //Tells the application the url to authorize the application.
        Uri siteLogonToken = new Uri("https://api-user.netflix.com/oauth/login");

        private string dataSource = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
        XmlDocument xmlDoc = new XmlDocument();
        XmlDocument xmlDoc1 = new XmlDocument();

        //Declares all of the xmlnodes for the Oauth security settings
        XmlNode node1, node2, node3, node4, node5, node6, nodeAppName, nodeConsumerKey;

        //Declares all of the xmlnodes for the movie ratings filter settings.
        XmlNode node7, node8, node9, node10, node11, node16, node17;

        //Declares all of the xmlnodes for the movie genre filters
        XmlNodeList node15;

        //Gets the Display/Quantity settings in the XML file
        XmlNode node12, node13;

        //Gets the DataRefresh settings in the XML file
        XmlNode node14;


        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                if (!System.IO.File.Exists(dataSource + @"\moviesformyblognetflixuser.xml"))
                {
                    CreateXMLFiles("user");
                }
                if (!System.IO.File.Exists(dataSource + @"\moviesformyblognetflixdata.xml"))
                {
                    CreateXMLFiles("data");
                }
                xmlDoc.Load(dataSource + @"\moviesformyblognetflixuser.xml");

                //Gets all of the Oauth security settings
                node1 = xmlDoc.SelectSingleNode("//LoginToken/oauth_token");
                node2 = xmlDoc.SelectSingleNode("//LoginToken/oauth_token_secret");
                node3 = xmlDoc.SelectSingleNode("//AuthorizedToken/oauth_token");
                node4 = xmlDoc.SelectSingleNode("//AccessToken/oauth_token");
                node5 = xmlDoc.SelectSingleNode("//AccessToken/user_id");
                node6 = xmlDoc.SelectSingleNode("//AccessToken/oauth_token_secret");
                nodeAppName = xmlDoc.SelectSingleNode("//LoginToken/application_name");
                nodeConsumerKey = xmlDoc.SelectSingleNode("//RequestToken/consumerkey");

                //Checks movie ratings filter settings to show what is active
                node7 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='G']");
                node8 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='PG']");
                node9 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='PG-13']");
                node10 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='R']");
                node11 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='NR']");
                node16 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='UR']");
                node17 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='NC-17']");

                //Gets the Display/Quantity settings in the XML file
                node12 = xmlDoc.SelectSingleNode("//FilterSettings/DisplayQuantity/control[@id='DiscsShipped']");
                node13 = xmlDoc.SelectSingleNode("//FilterSettings/DisplayQuantity/control[@id='InstantPlay']");

                //Gets the DataRefresh settings in the XML file
                node14 = xmlDoc.SelectSingleNode("//FilterSettings/DataRefresh/control[@id='time']");


                //Sets the GUI objects for the Oauth security settings
                txtLoginOauth.Text = node1.InnerText;
                txtLoginSecret.Text = node2.InnerText;
                txtAuthToken.Text = node3.InnerText;
                txtAccessToken.Text = node4.InnerText;
                txtAccessUserID.Text = node5.InnerText;
                txtAccessSecret.Text = node6.InnerText;
                txtConsumerKey.Text = nodeConsumerKey.InnerText;

                //Sets the GUI objects for the movie ratings settings
                cbGrating.Checked = Convert.ToBoolean(node7.Attributes["active"].InnerText);
                cbPGrating.Checked = Convert.ToBoolean(node8.Attributes["active"].InnerText);
                cbPG13rating.Checked = Convert.ToBoolean(node9.Attributes["active"].InnerText);
                cbRrating.Checked = Convert.ToBoolean(node10.Attributes["active"].InnerText);
                cbNRrating.Checked = Convert.ToBoolean(node11.Attributes["active"].InnerText);
                cbURrating.Checked = Convert.ToBoolean(node16.Attributes["active"].InnerText);
                cbNC17rating.Checked = Convert.ToBoolean(node17.Attributes["active"].InnerText);

                //Sets the GUI objects for the display quantity settings
                cbDVDdisplay.Checked = Convert.ToBoolean(node12.Attributes["active"].InnerText);
                txtDVDqty.Text = node12.Attributes["quantity"].InnerText;
                cbInstantDisplay.Checked = Convert.ToBoolean(node13.Attributes["active"].InnerText);
                txtInstantQty.Text = node13.Attributes["quantity"].InnerText;

                //Sets the GUI objects for the DataRefresh settings
                txtRefreshTime.Text = node14.Attributes["quantity"].InnerText;



                //*****Genre Filtering******
                //Queries the webservice to load genres into the system
                moviesformyblognetflix.Service mg = new moviesformyblognetflix.Service();

                xmlDoc1.LoadXml(mg.RequestMovieGenres().genres);

                XmlNodeList nlGenres = xmlDoc1.SelectNodes("//genre");

                //Adds the primary genres into the drop down list
                foreach (XmlNode n in nlGenres)
                {
                    ddlMovieGenres.Items.Add(n.Attributes["id"].InnerText);

                }
                //Selects all of the sub genres to load into the listbox
                XmlNodeList nlSubGenres = xmlDoc1.SelectNodes("//sub_genre[@term=\"" + ddlMovieGenres.Items[0].Text + "\"] | //sub_sub_genre[@term=\"" + ddlMovieGenres.Items[0].Text + "\"]");

                //Loads all the sub genres for the primary genre into the listbox
                foreach (XmlNode n in nlSubGenres)
                {
                    //Checks movie genres filter settings to show what needs to be put into the Blocked box for editing
                    node15 = xmlDoc.SelectNodes("//GenreFilters/Genre[@term=\"" + ddlMovieGenres.SelectedValue + "\" and @id=\"" + n.Attributes["id"].InnerText + "\"]");

                    if (node15.Count > 0)
                    {
                        foreach (XmlNode n1 in node15)
                        {
                            if (n1.Attributes["id"].InnerText == n.Attributes["id"].InnerText && n1.Attributes["term"].InnerText == n.Attributes["term"].InnerText)
                            {
                                lbGenreFilter.Items.Add(n.Attributes["id"].InnerText);
                            }
                            else
                            {
                                lbGenreAllowed.Items.Add(n.Attributes["id"].InnerText);
                            }
                        }
                    }
                    else
                    {
                        lbGenreAllowed.Items.Add(n.Attributes["id"].InnerText);
                    }

                }

                xmlDoc1.Save(dataSource + @"\moviesformyblognetflixgenre.xml");
                //*****Genre Filtering******

                if (txtLoginOauth.Text != "" && txtLoginSecret.Text != "")
                {

                    string url = siteLogonToken + "?application_name=" + nodeAppName.InnerText
                        + "&oauth_callback=" + Server.UrlEncode("_blank")
                        + "&oauth_consumer_key=" + nodeConsumerKey.InnerText
                        + "&oauth_token=" + node1.InnerText;
                    hlAuthorizedToken.NavigateUrl = url;

                }
            }
        }

        public override void Save()
        {

            xmlDoc.Load(dataSource + @"\moviesformyblognetflixuser.xml");

            //Selects movie ratings filter settings to apply the new settings to the xml file.
            node7 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='G']");
            node8 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='PG']");
            node9 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='PG-13']");
            node10 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='R']");
            node11 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='NR']");
            node16 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='UR']");
            node17 = xmlDoc.SelectSingleNode("//FilterSettings/Ratings/control[@id='NC-17']");

            //Sets all of the xml data to the GUI selected options
            node7.Attributes["active"].InnerText = cbGrating.Checked.ToString();
            node8.Attributes["active"].InnerText = cbPGrating.Checked.ToString();
            node9.Attributes["active"].InnerText = cbPG13rating.Checked.ToString();
            node10.Attributes["active"].InnerText = cbRrating.Checked.ToString();
            node11.Attributes["active"].InnerText = cbNRrating.Checked.ToString();
            node16.Attributes["active"].InnerText = cbURrating.Checked.ToString();
            node17.Attributes["active"].InnerText = cbNC17rating.Checked.ToString();

            //Gets the Display/Quantity settings in the XML file
            node12 = xmlDoc.SelectSingleNode("//FilterSettings/DisplayQuantity/control[@id='DiscsShipped']");
            node13 = xmlDoc.SelectSingleNode("//FilterSettings/DisplayQuantity/control[@id='InstantPlay']");

            //Gets the options for displaying instant and dvd and the quantity for each
            node12.Attributes["active"].InnerText = cbDVDdisplay.Checked.ToString();
            node12.Attributes["quantity"].InnerText = txtDVDqty.Text;
            node13.Attributes["active"].InnerText = cbInstantDisplay.Checked.ToString();
            node13.Attributes["quantity"].InnerText = txtInstantQty.Text;

            //Gets the DataRefresh settings in the XML file
            node14 = xmlDoc.SelectSingleNode("//FilterSettings/DataRefresh/control[@id='time']");

            //Gets the time for how often to refresh the data
            node14.Attributes["quantity"].InnerText = txtRefreshTime.Text;

            xmlDoc.Save(dataSource + @"\moviesformyblognetflixuser.xml");

            MoviesForMyBlog mfmb = new MoviesForMyBlog();
            mfmb.RefreshMovieData();

        }

        //Get the login token needed to authorize movies for my blog to your netflix account
        protected void lbLoginTokens_Click(object sender, EventArgs e)
        {
            xmlDoc.Load(dataSource + @"\moviesformyblognetflixuser.xml");
            XmlNode node = xmlDoc.SelectSingleNode("//RequestToken/consumerkey");

            moviesformyblognetflix.Service ws = new moviesformyblognetflix.Service();
            string strLogin = ws.RequestLoginToken(node.InnerText);

            char[] delimiterChars1 = { '&', '=' };
            string[] words1 = strLogin.Split(delimiterChars1);

            XmlNode node1 = xmlDoc.SelectSingleNode("//LoginToken/oauth_token");
            XmlNode node2 = xmlDoc.SelectSingleNode("//LoginToken/oauth_token_secret");
            XmlNode node3 = xmlDoc.SelectSingleNode("//AuthorizedToken/oauth_token");
            node1.InnerText = words1[1];
            node2.InnerText = words1[3];
            node3.InnerText = words1[1];

            xmlDoc.Save(dataSource + @"\moviesformyblognetflixuser.xml");

            txtLoginOauth.Text = words1[1];
            txtLoginSecret.Text = words1[3];

            XmlNode nodeAppName = xmlDoc.SelectSingleNode("//LoginToken/application_name");
            XmlNode nodeConsumerKey = xmlDoc.SelectSingleNode("//RequestToken/consumerkey");
            string url = siteLogonToken + "?application_name=" + nodeAppName.InnerText
                + "&oauth_callback=" + Server.UrlEncode("_blank")
                + "&oauth_consumer_key=" + nodeConsumerKey.InnerText
                + "&oauth_token=" + words1[1];
            hlAuthorizedToken.NavigateUrl = url;

            txtAuthToken.Text = words1[1];

        }

        //Gets the access tokens required to make calls to netflix with your account  
        protected void lbAccessToken_Click(object sender, EventArgs e)
        {
            try
            {
                xmlDoc.Load(dataSource + @"\moviesformyblognetflixuser.xml");

                XmlNode node = xmlDoc.SelectSingleNode("//RequestToken/consumerkey");
                XmlNode node1 = xmlDoc.SelectSingleNode("//LoginToken/oauth_token");
                XmlNode node2 = xmlDoc.SelectSingleNode("//LoginToken/oauth_token_secret");

                moviesformyblognetflix.Service ws = new moviesformyblognetflix.Service();
                string strLogin = ws.RequestAccessToken(node.InnerText, node1.InnerText + "&" + node2.InnerText);

                char[] delimiterChars1 = { '&', '=' };
                string[] words1 = strLogin.Split(delimiterChars1);


                XmlNode node4 = xmlDoc.SelectSingleNode("//AccessToken/oauth_token");
                XmlNode node5 = xmlDoc.SelectSingleNode("//AccessToken/user_id");
                XmlNode node6 = xmlDoc.SelectSingleNode("//AccessToken/oauth_token_secret");

                node4.InnerText = words1[1];
                node5.InnerText = words1[3];
                node6.InnerText = words1[5];

                xmlDoc.Save(dataSource + @"\moviesformyblognetflixuser.xml");

                txtAccessToken.Text = words1[1];
                txtAccessUserID.Text = words1[3];
                txtAccessSecret.Text = words1[5];
            }
            catch
            {


            }

        }

        //Create the XML files needed to power this plugin when it is first installed.
        private void CreateXMLFiles(string strXML)
        {
            XmlDocument xmlDoc = new XmlDocument();
            switch (strXML)
            {
                case "user":
                    string xmlString = @"<?xml version='1.0' encoding='utf-8'?>";
                    xmlString += "<data>";
                    xmlString += "<RequestToken>";
                    xmlString += "<consumerkey>qdgmvxswkxqqhxhdnhantdst</consumerkey>";
                    xmlString += "</RequestToken>";
                    xmlString += "<LoginToken>";
                    xmlString += "<oauth_token></oauth_token>";
                    xmlString += "<oauth_token_secret></oauth_token_secret>";
                    xmlString += "<application_name>Movies+For+My+Blog</application_name>";
                    xmlString += "</LoginToken>";
                    xmlString += "<AuthorizedToken>";
                    xmlString += "<oauth_token></oauth_token>";
                    xmlString += "</AuthorizedToken>";
                    xmlString += "<AccessToken>";
                    xmlString += "<oauth_token></oauth_token>";
                    xmlString += "<user_id></user_id>";
                    xmlString += "<oauth_token_secret></oauth_token_secret>";
                    xmlString += "</AccessToken>";
                    xmlString += "<FilterSettings>";
                    xmlString += "<Ratings>";
                    xmlString += "<control id=\"G\" active=\"True\"></control>";
                    xmlString += "<control id=\"PG\" active=\"True\"></control>";
                    xmlString += "<control id=\"PG-13\" active=\"True\"></control>";
                    xmlString += "<control id=\"R\" active=\"True\"></control>";
                    xmlString += "<control id=\"NC-17\" active=\"True\"></control>";
                    xmlString += "<control id=\"NR\" active=\"True\"></control>";
                    xmlString += "<control id=\"UR\" active=\"True\"></control>";
                    xmlString += "</Ratings>";
                    xmlString += "<DisplayQuantity>";
                    xmlString += "<control id=\"DiscsShipped\" active=\"True\" quantity=\"10\"></control>";
                    xmlString += "<control id=\"InstantPlay\" active=\"True\" quantity=\"10\"></control>";
                    xmlString += "</DisplayQuantity>";
                    xmlString += "<DataRefresh>";
                    xmlString += "<control id=\"time\" quantity=\"1\"></control>";
                    xmlString += "</DataRefresh>";
                    xmlString += "<GenreFilters>";
                    xmlString += "<Genre />";
                    xmlString += "</GenreFilters>";
                    xmlString += "</FilterSettings>";
                    xmlString += "</data>";
                    xmlDoc.LoadXml(xmlString);
                    xmlDoc.Save(dataSource + @"\moviesformyblognetflixuser.xml");
                    break;

                case "data":
                    XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                    XmlElement root = xmlDoc.CreateElement("data");
                    root.InnerText = "new";
                    xmlDoc.AppendChild(root);
                    xmlDoc.InsertBefore(dec, root);

                    xmlDoc.Save(dataSource + @"\moviesformyblognetflixdata.xml");
                    break;

            }

        }




        protected void lbFilters_Click(object sender, EventArgs e)
        {
            mfmbMultiView.SetActiveView(viewFilters);
        }
        protected void lbSettings_Click(object sender, EventArgs e)
        {
            mfmbMultiView.SetActiveView(viewSettings);
        }


        protected void ddlMovieGenres_SelectedIndexChanged(object sender, EventArgs e)
        {
            //loads up the movie and genres
            xmlDoc.Load(dataSource + @"\moviesformyblognetflixuser.xml");
            xmlDoc1.Load(dataSource + @"\moviesformyblognetflixgenre.xml");
            XmlNodeList nlSubGenres = xmlDoc1.SelectNodes("//sub_genre[@term=\"" + ddlMovieGenres.SelectedValue + "\"] | //sub_sub_genre[@term=\"" + ddlMovieGenres.SelectedValue + "\"]");

            lbGenreAllowed.Items.Clear();
            lbGenreFilter.Items.Clear();


            //Loads into the listbox according to what has been selected
            foreach (XmlNode n in nlSubGenres)
            {
                //Checks movie genres filter settings to show what needs to be put into the Blocked box for editing
                node15 = xmlDoc.SelectNodes("//GenreFilters/Genre[@term=\"" + ddlMovieGenres.SelectedValue + "\" and @id=\"" + n.Attributes["id"].InnerText + "\"]");
                if (node15.Count > 0)
                {
                    foreach (XmlNode n1 in node15)
                    {
                        if (n1.Attributes["id"].InnerText == n.Attributes["id"].InnerText && n1.Attributes["term"].InnerText == n.Attributes["term"].InnerText)
                        {
                            lbGenreFilter.Items.Add(n.Attributes["id"].InnerText);
                        }
                        else
                        {
                            lbGenreAllowed.Items.Add(n.Attributes["id"].InnerText);
                        }
                    }
                }
                else
                {
                    lbGenreAllowed.Items.Add(n.Attributes["id"].InnerText);
                }

            }

        }

        //Updates the user data xml file based on options that they have selected to be blocked
        protected void lbGenreAllowed_SelectedIndexChanged(object sender, EventArgs e)
        {

            xmlDoc.Load(dataSource + @"\moviesformyblognetflixuser.xml");
            XmlNode root = xmlDoc.SelectSingleNode("//GenreFilters");
            XmlElement xe = xmlDoc.CreateElement("Genre");
            xe.SetAttribute("id", lbGenreAllowed.SelectedValue);
            xe.SetAttribute("term", ddlMovieGenres.SelectedValue);
            root.AppendChild(xe);

            xmlDoc.Save(dataSource + @"\moviesformyblognetflixuser.xml");
            lbGenreFilter.Items.Add(lbGenreAllowed.SelectedValue);
            lbGenreAllowed.Items.Remove(lbGenreAllowed.SelectedValue);

            SortedList sl = new SortedList();
            foreach (ListItem l1 in lbGenreFilter.Items)
            {
                sl.Add(l1.Text, l1);
            }
            lbGenreFilter.Items.Clear();

            for (int i = 0; i < sl.Count; i++)
            {
                lbGenreFilter.Items.Add((ListItem)sl[sl.GetKey(i)]);
            }

        }

        //Removes genres from the user data xml to move it back to approved.
        protected void lbGenreFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            xmlDoc.Load(dataSource + @"\moviesformyblognetflixuser.xml");
            XmlNode removenode = xmlDoc.SelectSingleNode("//GenreFilters/Genre[@term=\"" + ddlMovieGenres.SelectedValue + "\" and @id=\"" + lbGenreFilter.SelectedValue + "\"]");
            removenode.ParentNode.RemoveChild(removenode);
            xmlDoc.Save(dataSource + @"\moviesformyblognetflixuser.xml");
            lbGenreAllowed.Items.Add(lbGenreFilter.SelectedValue);
            lbGenreFilter.Items.Remove(lbGenreFilter.SelectedValue);

            SortedList sl = new SortedList();
            foreach (ListItem l1 in lbGenreAllowed.Items)
            {
                sl.Add(l1.Text, l1);
            }
            lbGenreAllowed.Items.Clear();

            for (int i = 0; i < sl.Count; i++)
            {
                lbGenreAllowed.Items.Add((ListItem)sl[sl.GetKey(i)]);
            }
        }
    }
}
